import { Message } from 'view-design'
import encryption from '@/libs/encryption.js';
import { getdatalist } from '@/api/login.js';
import router from '../router';
import store from '../store';
import designer_menu_config from './designer_menu';
import mockMenuapi from "./mockMenuapi2";
import {getDictInfoByName} from "../api/dict";

let markMenuObj = {} // 每个父路由的子路由路径
const parentView = () => import('@/components/parent-view');
let roleShowMenu = {};
const staticMenu = {}
for (let key in designer_menu_config) {
    let type = designer_menu_config[key].type;
    if (type === 'static') {
        staticMenu[key] = {...designer_menu_config[key],name:key};
    }
}
const staticMenuArr = Object.values(staticMenu)
// 获取菜单列表
let getLoading = false;
const getMenuList = async (to, next) => {
    if (getLoading) {
        return;
    }
    getMicroConfig() // 微服务的配置也属于菜单的信息也放到这里吧
    roleShowMenu = dealShowMenu();
    // let storeMenu = getStoreMenu();
    // if (storeMenu.length > 0) {
    //     let routeList = formatRoutes(storeMenu, 'main');
    //     // 菜单
    //     store.commit('setRouteList', routeList);
    //     next();
    // }
    getLoading = true;
    //渲染菜单栏(后台的菜单数据) { type: 'designer' }
    // let res = await getdatalist({ platformType: 'designer' }).catch(error => {
    //     sessionStorage.setItem('d_menu_data', []);
    //     store.commit('setRouteList', []);
    //     store.commit('setflatList', []);
    //     return 0
    // });

    let data = {code:1,data:[]}
    let res = {data:data}
    getLoading = false;
    if(!res){
        return
    }
    if (res.data.code == 1) {
       
        let data = res.data.data;

        sessionStorage.setItem('d_menu_data', encryption.SelfUseEncrypt(JSON.stringify(data)));
        // 菜单数据处理成路由再
        let routeList = formatRoutes(data, 'main');
        sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj)); // 微服务跳转需要，不然从微服务路由，跳不是微的父路由找不到地址
        // console.log(routeList);
        let distributedRange = data.some((item) => {
            return item.key == 'distributedRange';
        });
        store.commit('user/serDistributedRange', distributedRange);
        // 菜单
        store.commit('setRouteList', routeList);
        const flatMenuData = flatList(data);
        store.commit('setflatList', flatMenuData);
        // console.log(routeList)
        if (to.name == 'main') {
            next({ name: routeList.length > 0 ? routeList[0].name : '' });
        } else {
            next({ ...to}); //进行路由跳转
        }
        return 1
    }else {
        Message.error(res.data.message)
        sessionStorage.setItem('d_menu_data', []);
        store.commit('setRouteList', []);
        store.commit('setflatList', []);
        return 0
    }
};
// 菜单数据处理成路由
const formatRoutes = (menuList, parentName = 'main',pmenu) => {
    let routeList = [];
    let configMenu = roleShowMenu;
    dealStaticMenu(menuList,parentName,pmenu);//处理由前端控制的菜单数据
    menuList.sort((a,b) => a.sort - b.sort);
    menuList.forEach((menu) => {
        let route = {};
        let { key, name, children = [], parentId, icon: configIcon, hide } = menu;
        let redirectMenu = children && (children.find((item) => configMenu[item.key] || flatList(item.children).find(child => configMenu[child.key])));
        // hide 取反：隐藏的菜单hide 为true 所以取反
        if ((configMenu[menu.key] || (!configMenu[menu.key] && redirectMenu)) && !hide) {
            //前端配置了菜单信息
            let { icon='drill-icon', component,path } = configMenu[menu.key] || {};
            route = {
                path: path||`/${key}`,// path 这个系统只有微服务子应用路径这么配置
                name: key,
                title: name,
                hidden: true,
                icon: configIcon, //如果后台配置了icon
                meta: {
                    title: name,
                    requireAuth: true,
                },
            };
            if (parentId === '0') {
                route.meta.defClass = `${icon}-def`;
                route.meta.activeClass = `${icon}-active`;
            }
            if (route.name == 'archiveReports' || route.name == 'filing') {
              // 归档管理
              store.commit('compet/setHasFile', true)
            }
            if (['fzDrill','hwDrill','swDrill','zcDrill','dailyDrill'].includes(route.name)) {
                //护网演练
                sessionStorage.setItem('isRetainer', true);
            }
            let hasChildren = children && children instanceof Array && children.length > 0;
            let hasStaticChildren = staticMenuArr.find(item => item.parent === key);
            // let redirectMenu = children && (children.find((item) => configMenu[item.key] || flatList(item.children).find(child => configMenu[child.key])));
            if (hasChildren && redirectMenu) {
                route.component = parentView; //有children的菜单都用parentView 组件

                let keySon = redirectMenu.key
                let dMenu = roleShowMenu[keySon] // 如果designer_menu.js 配置了path 优先跳转到path 
                route.redirect = dMenu.path||`/${redirectMenu.key}`; //如果没有配置，默认重定向到第一个// redirect || 
                // console.log('父路由',name,key,'对应第一个儿子',keySon,dMenu)
                markMenuObj[key] = keySon
                // console.log('跳转到子路由的路径，',route.redirect)
            } else if(hasStaticChildren) {
                route.component = parentView; //有children的菜单都用parentView 组件
                route.redirect = `/${hasStaticChildren.name}`
            } else {
                route.component = component;
            }
            if(route.component || path){ // path 的是子应用系统
                let routes = router.getRoutes();
                if (!routes.find((item) => item.name === key)) {
                    router.addRoute(parentName, route);
                    //console.log('--------- router.addRoute-------',parentName,route.title,route)
                }
                if (hasChildren || hasStaticChildren) {
                    route.children = formatRoutes(children, key,menu);
                }
                routeList.push(route);
            }
        }
    });
    // console.log('----routeList----',routeList)
    return routeList;
};
// 处理由前端控制的菜单
const dealStaticMenu = (menuList,parentName,pmenu) => {
    for (let key in staticMenu) {
        //按角色过滤显示菜单
        let parent = staticMenu[key].parent || 'main';
        if (parent === parentName) {
            menuList.push({
                children: [],
                key: key,
                name: staticMenu[key].title,
                parentId: pmenu ? pmenu.id : '0',
                sort: staticMenu[key].sort
            });
        }
    }
}
// 角色显示的菜单, 不过滤角色 
const dealShowMenu = () => {
    //return designer_menu_config
    let configMenu = {};
    let role = store.state.user.role; //用户角色
    for (let key in designer_menu_config) {
        //按角色过滤显示菜单
        let showRole = designer_menu_config[key].showRole;
        if (!showRole || showRole.includes(role)) {
            configMenu[key] = designer_menu_config[key];
        }
    }
    return configMenu
}
const getMicroConfig = () => { // 可以不配置不配置用默认的就行
    getDictInfoByName({name: 'microappDesignerUrl'}).then(({ code, attribute, message }) => {
        if (code == 1) {
            //console.log(attribute.data.value,'字典的信息啊啊啊-----------')
            // sessionStorage.setItem('mmm', attribute.data.value);
            if(attribute && attribute.data && attribute.data.value){
                sessionStorage.setItem('mmm', encryption.SelfUseEncrypt(JSON.stringify(attribute.data.value)));
                return
            }
        }else {
            sessionStorage.removeItem('mmm');
        }
        
    })
}



// 获取存储菜单数据
const getStoreMenu = () => {
    let menuData = sessionStorage.getItem('d_menu_data');
    if (menuData) {
        menuData = JSON.parse(encryption.SelfUseDecrypt(menuData));
        return menuData;
    }
    return [];
};
const dealParentViewPage = (to, from, next) => {
    //详情页对应多个菜单的，加个fromMenu用来匹配菜单
    if (
        to.matched.some((item) => item.name === 'parentView') &&
        !to.query.fromMenu &&
        Array.isArray(to.meta.activeName) &&
        from.name
    ) {
        if(from.matched.every((item) => item.name !== 'parentView')){ //菜单页跳到详情页
            to.query.fromMenu = from.name;
        }else{  //详情页跳到详情页
            if(from.query.fromMenu){
                to.query.fromMenu = from.query.fromMenu;
            }else{
                to.query.fromMenu = from.meta.activeName
            }
        }
        next({ ...to });
    }
};

// 递归扁平化  目前使用path title
const flatList = (data,chilldrenParams = 'children') => {
    let result = []
    data.forEach(item => {
        if(!item.hide){
            result.push({name:item.key,title:item.name,hide:item.hide});
            item.children && result.push(...flatList(item[chilldrenParams]))
        }
    })
    return result
}
export { getMenuList,dealParentViewPage };
